from flask import Flask,request,json,jsonify,render_template
# 接收上传的文件
import os,random,string,threading

# 上一级目录路径
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
             
# 获取upload文件夹的相对路径
UPLOAD_FOLDER = os.path.join('static', 'upload')

def upload():
    # 接收上传的文件 处理异常
    try:
        f = request.files['file']
        # 随机文件名
        f.filename = ''.join(random.sample(string.ascii_letters + string.digits, 16)) + '.' + f.filename.rsplit('.', 1)[1]
        # 保存文件
        filedir = os.path.join(UPLOAD_FOLDER, f.filename)
        f.save(filedir)
        # 异步运行上传的脚本
        t = threading.Thread(target=run, args=(filedir,))
        t.start()
        return jsonify({'code': 200, 'msg': '上传成功'})
    except Exception as e:
        return jsonify({'code': 500, 'msg': '上传失败'})


# 异步运行上传的脚本
def run(filedir):
    # 异步运行上传的脚本
    print('开始执行脚本')
    os.system('python ' + filedir)
    print('脚本执行完毕')

if __name__ == '__main__':
    pass